package com.fancy.application.sys.rest.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fancy.application.common.Interceptor.wrapper.FancyHttpServletRequestWrapper;
import com.fancy.application.common.enums.SuccessEnumeration;
import com.fancy.application.common.utils.IPAddressUtil;
import com.fancy.application.common.vo.Result;
import com.fancy.application.sys.rest.entity.SysRestLog;
import com.fancy.application.sys.rest.entity.SysRestMain;
import com.fancy.application.sys.rest.service.ISysRestConstants;
import com.fancy.application.sys.rest.service.ISysRestLogService;
import com.fancy.application.sys.rest.service.ISysRestMainService;
import lombok.extern.log4j.Log4j2;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问接口的拦截器，控制权限
 */
@Log4j2
@Component
public class SysRestMainInterceptor implements HandlerInterceptor, ISysRestConstants {
    @Resource
    private ISysRestMainService sysRestMainService;
    @Resource
    private ISysRestLogService sysRestLogService;


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, Object o) throws Exception {
        String sourceIp = IPAddressUtil.getIPAddress(httpServletRequest);
        String requestURI = httpServletRequest.getRequestURI();
        log.debug("请求的链接是。。。{}", requestURI);
        log.info("请求的ip:{}", sourceIp);
        if(StrUtil.equals("/rest-api/generateToken",requestURI)){
            return true;
        }
        CheckURIResult checkURIResult = sysRestMainService.isAllowed(httpServletRequest);
        if(checkURIResult.getPass()){//请求拦截通过。
            StopWatch stopWatch = new StopWatch();
            stopWatch.start(httpServletRequest.getRequestURI());
            SysRestMain sysRestMain =sysRestMainService.getRestMainByURI(requestURI);
            if(sysRestMain!=null){
                SysRestLog log = new SysRestLog();
                log.setFdServiceIp(sourceIp);
                log.setFdParam(getParam(httpServletRequest));
                log.setFdServiceKey(sysRestMain.getFdServiceKey());
                log.setFdRestId(sysRestMain.getFdId());
                httpServletRequest.setAttribute(ISysRestLogService.interceptorKey,log);
                httpServletRequest.setAttribute(ISysRestLogService.interceptorStopWatch,stopWatch);
            }
            return true;
        }else{
            httpServletResponse.setStatus(200);
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            Result result = Result.error(checkURIResult.getMsg());

            JSONObject jsonObject = JSONUtil.parseObj(result);
            httpServletResponse.getWriter().write(jsonObject.toString());
            httpServletResponse.getWriter().flush();
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
        SysRestLog log = (SysRestLog) httpServletRequest.getAttribute(ISysRestLogService.interceptorKey);
        StopWatch stopWatch = (StopWatch) httpServletRequest.getAttribute(ISysRestLogService.interceptorStopWatch);
        if(stopWatch!=null){
            stopWatch.stop();
            log.setFdExecuteTime(stopWatch.getTotalTimeMillis());
        }
        if(log!=null){
            log.setFdExecuteResult(SuccessEnumeration.SUCCESS.name());
            sysRestLogService.save(log);
        }


    }


    private String getParam(HttpServletRequest request) throws IOException {
        FancyHttpServletRequestWrapper wrapper = new FancyHttpServletRequestWrapper(request);
        return wrapper.getBodyString();
    }
}
